package com.yzyz.management.web;

import java.io.IOException;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import net.sf.json.JSONArray;
import net.sf.json.JsonConfig;

import org.springframework.web.servlet.mvc.multiaction.MultiActionController;

import com.yzyz.bean.scenic.DescriptionBean;
import com.yzyz.bean.scenic.ScenicBean;
import com.yzyz.service.DescriptionService;
import com.yzyz.service.ScenicService;
import com.yzyz.utils.ValidateUtils;
import com.yzyz.utils.error.ErrorBean;
import com.yzyz.utils.json.management.JSONScenicForRoute;
import com.yzyz.utils.json.management.JSONScenicM;
import com.yzyz.utils.error.Error;

/**
 * Manage scenic
 * @author David Sun
 * @Date   2010-3-15
 *
 */
public class ScenicController extends MultiActionController {
	private ScenicService scenicService;
	private DescriptionService descriptionService;
	public void setDescriptionService(DescriptionService descriptionService) {
		this.descriptionService = descriptionService;
	}
	public void setScenicService(ScenicService scenicService) {
		this.scenicService = scenicService;
	}
	@SuppressWarnings("unchecked")
	public void getScenics(HttpServletRequest request, HttpServletResponse response) throws IOException{
		int start = Integer.valueOf(request.getParameter("start"));
		int limit = Integer.valueOf(request.getParameter("limit"));
		int groupId = -1;
		if(!ValidateUtils.isNull(request.getParameter("groupId"))) {
			groupId = Integer.valueOf(request.getParameter("groupId"));
		}
		List<ScenicBean> list = (List<ScenicBean>)this.scenicService.paginate(start, limit, request.getParameter("searchName"), groupId);
		List<JSONScenicM> js = new ArrayList<JSONScenicM>();
		if(list != null) {
			for(ScenicBean scenic: list) {
				JSONScenicM s = new JSONScenicM(scenic);
				js.add(s);
			}
		}
		JSONArray arr = JSONArray.fromObject(js, JSONScenicM.getConfig());
		StringBuffer sb 			= new StringBuffer();
		sb.append("{\"sum\":").append("\""+this.scenicService.getCountAll(request.getParameter("searchName"), groupId)+"\",");
		sb.append("\"data\":").append(arr.toString());
		sb.append("}");
		this.writeToClient(response, sb.toString());
	}
	/**
	 * 添加新的景区，在添加景区的同时也要添加景区描述
	 * @param request
	 * @param response
	 * @throws IOException 
	 */
	public void add(HttpServletRequest request, HttpServletResponse response) throws IOException{
		ScenicBean scenic = new ScenicBean();
		scenic.setAvailable(true);
		scenic.setDate(new Date());
		scenic.setLevel(Integer.valueOf(request.getParameter("level")));
		scenic.setLocation(request.getParameter("location"));
		scenic.setName(request.getParameter("name"));
		scenic.setOwnerId(Integer.valueOf(request.getParameter("ownerId")));
		this.scenicService.add(scenic, request.getParameter("description"));
		ErrorBean error = ErrorBean.getInstance(Error.SUCCESS,"添加成功", scenic.getId());
		this.writeToClient(response, error.toJson());
	}
	public void getInfo(HttpServletRequest request, HttpServletResponse response) throws IOException{
		if(ValidateUtils.isNull(request.getParameter("scenicId"))){
			ErrorBean error = new ErrorBean();
			error.setCode(Error.FETCH_INFO_FAILED);
			this.writeToClient(response, error.toJson());
			return;
		}
		int scenicId = Integer.valueOf(request.getParameter("scenicId"));
		ScenicBean scenic = (ScenicBean) this.scenicService.find(scenicId);
		if(scenic == null) {
			ErrorBean error = new ErrorBean();
			error.setCode(Error.OBJECT_NOT_EXIST);
			error.setMessage(Error.errorMsg[error.getCode()]);
			this.writeToClient(response, error.toJson());
			return;
		}
	}
	/**
	 * 禁止某个景区
	 * @param request
	 * @param response
	 * @throws IOException 
	 */
	public void disable(HttpServletRequest request, HttpServletResponse response) throws IOException{
		this.scenicService.updateAvailable(Integer.valueOf(request.getParameter("scenicId")), false);
		this.writeToClient(response, ErrorBean.getSuccessMsg());
	}
	/**
	 * 激活某个景区
	 * @param request
	 * @param response
	 * @throws IOException 
	 */
	public void enable(HttpServletRequest request, HttpServletResponse response) throws IOException{
		this.scenicService.updateAvailable(Integer.valueOf(request.getParameter("scenicId")), true);
		this.writeToClient(response, ErrorBean.getSuccessMsg());
	}
	/**
	 * 删除景区
	 * @param request
	 * @param response
	 * @throws IOException 
	 */
	public void delete(HttpServletRequest request, HttpServletResponse response) throws IOException{
		this.scenicService.delete(Integer.valueOf(request.getParameter("scenicId")));
		this.writeToClient(response, ErrorBean.getSuccessMsg());
	}
	
	/**
	 * 更新景区
	 * @param request
	 * @param response
	 * @throws IOException 
	 */
	public void update(HttpServletRequest request, HttpServletResponse response) throws IOException{
		ScenicBean scenic = new ScenicBean();
		scenic.setLevel(Integer.valueOf(request.getParameter("level")));
		scenic.setLocation(request.getParameter("location"));
		scenic.setName(request.getParameter("name"));
		scenic.setOwnerId(Integer.valueOf(request.getParameter("ownerId")));
		scenic.setId(Integer.valueOf(request.getParameter("scenicId")));
		this.scenicService.update(scenic);
		this.writeToClient(response, ErrorBean.getSuccessMsg());

	}
	
	/**
	 * 获取景区的描述
	 * @param request
	 * @param response
	 * @throws IOException
	 */
	public void getDescription(HttpServletRequest request, HttpServletResponse response) throws IOException{
		DescriptionBean des = (DescriptionBean)this.descriptionService.findByScenic(Integer.valueOf(request.getParameter("scenicId")));
		ErrorBean error=null;
		if(des==null){
			error = ErrorBean.getInstance(Error.SUCCESS, "", -1);
		}else {
			error = ErrorBean.getInstance(Error.SUCCESS, des.getContents(), des.getId());
		}
		this.writeToClient(response, error.toJson());
	}
	
	/**
	 * 更新景区描述
	 * @param request
	 * @param response
	 * @throws IOException
	 */
	public void updateDescription(HttpServletRequest request, HttpServletResponse response) throws IOException{
		DescriptionBean des = new DescriptionBean();
		des.setOwnerId(Integer.valueOf(request.getParameter("scenicId")));
		des.setContents(request.getParameter("contents"));
		this.descriptionService.update(des);
		this.writeToClient(response, ErrorBean.getSuccessMsg());
	}
	
	/**
	 * 获取某个路线关联的景区
	 * @param request
	 * @param response
	 * @throws IOException 
	 */
	public void getUsed(HttpServletRequest request, HttpServletResponse response) throws IOException{
		List<ScenicBean> list = this.scenicService.listUsed(Integer.valueOf(request.getParameter("routeId")));
		if(list==null){
			list = new ArrayList<ScenicBean>();
		}
		JsonConfig config = new JsonConfig();
		config.setExcludes(new String[]{"date","level","location"});
		JSONArray arr = JSONArray.fromObject(list, config);
		StringBuffer sb 			= new StringBuffer();
		sb.append("{\"sum\":").append("\""+list.size()+"\",");
		sb.append("\"data\":").append(arr.toString());
		sb.append("}");
		this.writeToClient(response, sb.toString());
	}
	
	/**
	 * 获取与某个线路相关的所有景区
	 * @param request
	 * @param response
	 * @throws IOException
	 */
	public void getScenicsForRoute(HttpServletRequest request, HttpServletResponse response) throws IOException{
		int start = Integer.valueOf(request.getParameter("start"));
		int limit = Integer.valueOf(request.getParameter("limit"));
		List<ScenicBean> used = this.scenicService.listUsed(Integer.valueOf(request.getParameter("routeId")));
		List<ScenicBean> list = this.scenicService.listAllByRegion(Integer.valueOf(request.getParameter("regionId")), start, limit);
		List<JSONScenicForRoute> js = new ArrayList<JSONScenicForRoute>();
		if(list != null && used !=null){
			for(ScenicBean scenic: list){//找出已经使用的
				for(int i = 0; i < used.size(); i ++){
					ScenicBean usedScenic = used.get(i);
					if(usedScenic.getId() == scenic.getId()){
						JSONScenicForRoute fr = new JSONScenicForRoute(scenic, true);
						js.add(fr);
						break;
					}
					if(i == (used.size() - 1)){
						JSONScenicForRoute fr = new JSONScenicForRoute(scenic, false);
						js.add(fr);
					}
				}
			}

			for(ScenicBean usedScenic: used){//去掉已经使用的
				for(int i=0; i < list.size(); i ++){
					if(list.get(i).getId() == usedScenic.getId()){
						list.remove(i);
						break;
					}
				}
			}
			for(ScenicBean scenic: list){
				JSONScenicForRoute fr = new JSONScenicForRoute(scenic, false);
				js.add(fr);
			}

		}
		JSONArray arr = JSONArray.fromObject(js, JSONScenicM.getConfig());
		StringBuffer sb = new StringBuffer();
		sb.append("{\"sum\":").append("\""+this.scenicService.getCountByRegion(Integer.valueOf(request.getParameter("regionId")))+"\",");
		sb.append("\"data\":").append(arr.toString());
		sb.append("}");
		this.writeToClient(response, sb.toString());
		
	}
	
	/**
	 * 取消某个线路与景区的关联
	 * @param request
	 * @param response
	 * @throws IOException
	 */
	public void cancel(HttpServletRequest request, HttpServletResponse response) throws IOException{
		this.scenicService.cancelUsedScenic(Integer.valueOf(request.getParameter("routeId")), Integer.valueOf(request.getParameter("scenicId")));
		this.writeToClient(response, ErrorBean.getSuccessMsg());
	}
	/**
	 * 添加某个线路与景区的关联
	 * @param request
	 * @param response
	 * @throws IOException 
	 */
	public void use(HttpServletRequest request, HttpServletResponse response) throws IOException{
		this.scenicService.addUsedScenic(Integer.valueOf(request.getParameter("routeId")), Integer.valueOf(request.getParameter("scenicId")));
		this.writeToClient(response, ErrorBean.getSuccessMsg());
	}
	
	private void writeToClient(HttpServletResponse response, String contents) throws IOException {
		response.setHeader("Cache-Control", "no-cache");
		response.setHeader("Programa", "no-cache");
		response.setDateHeader("Expires", -1L);
		response.setContentType("text/html; charset=UTF-8");
		response.getWriter().write(contents);
		response.flushBuffer();
		response.getWriter().close();
	}
}
